package iNotes;

import iNotes.assist.DataPool;
import iNotes.assist.Utils;

import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "AcceptItem", value = "/AcceptItem")
public class AcceptItem extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        return;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if(!Utils.checkToken(session,request)){
            response.getWriter().write("CSRF attack detected!");
            return;
        }
        int isAccept = request.getParameter("type").equals("accept") ? 1 : 0;
        int noteID = Integer.parseInt(request.getParameter("source"));
        int senderID = Integer.parseInt(request.getParameter("sender"));
        int uid = (int) session.getAttribute("uid");

        Connection connection = null;
        CallableStatement callableStatement = null;
        try {
            connection = DataPool.ds.getConnection();
            callableStatement = connection.prepareCall("{call receiveItem(?,?,?,?)}");
            callableStatement.setInt(1,senderID);
            callableStatement.setInt(2,noteID);
            callableStatement.setInt(3,uid);
            callableStatement.setInt(4,isAccept);
            callableStatement.execute();
        } catch (SQLException throwables) {
            if(throwables.getClass() == SQLIntegrityConstraintViolationException.class){
                System.err.println("User shared same notes.");
                session.setAttribute("duplicatedNote","true");
            }else{
                throwables.printStackTrace();
            }
        } finally {
            Utils.close(connection,null,callableStatement);
        }
        response.sendRedirect("notes.jsp");
    }
}
